package com.study.demo.aop.demo1;

import com.study.demo.aop.util.RandomUtils;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.cache.annotation.CachePut;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.Random;

/**
 * @author: elvin
 * @time: 2019-05-21 09:46
 * @desc:
 **/
public class UserService implements IUserService {
    //Cacheable 会检查缓存, 如果有, 则直接返回
    @Override
    //@Cacheable(value = "myCache", key = "'getDefault'")
    public User getDefault() {
        System.out.println("getDefault get from db...");
        User u = new User();
        u.setId(1);
        u.setName("xiaoming");
        u.setAge(18);
        return u;
    }

    //CacheEvict 是用来清除缓存的,
    // beforeInvocation = true 表示在这个方法之前就清除缓存,
    // beforeInvocation = false 表示在这个方法之后才清除缓存
    @Override
    //@CacheEvict(value = "myCache", key = "'getById_' + #id", beforeInvocation = false)
    public void clearBy(int id) {
        System.out.println("clear cache by clearBy(" + id + ")");
    }

    @Override
    //@Cacheable(value = "myCache", key = "'getById_' + #id")
    public User getById(int id) {
        System.out.println("getById(" + id + ") get from db...");
        User u = new User();
        u.setId(id);
        u.setName(RandomUtils.getRandomLetter(5));
        u.setAge(new Random().nextInt());
        return u;
    }

    //CachePut 是用来更新缓存的, 并不会检查缓存是否存在
    @Override
    //@CachePut(value = "myCache", key = "'getById_' + #id")
    public User getByIdPut(int id) {
        System.out.println("getByIdPut(" + id + ") get from db...");
        User u = new User();
        u.setId(id);
        u.setName(RandomUtils.getRandomLetter(5));
        u.setAge(new Random().nextInt());
        return u;
    }
}
